<script>
import {userLogin} from "@/api/user";

export default {
  name: "Index",
  data() {
    return {
      labelPosition: 'left',
      form: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  methods:{
    onSubmit(){
      //  获取组件中所有含有ref属性的标签对象
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 数据符合要求    发送http请求  判定用户名和密码是否正确
          userLogin(this.form.username,this.form.password).then(response=>{
            if (response.code==200){
              this.$message.success(response.message)
              // 验证通过  跳转页面到主页面
              this.$router.push('/home')
            }else {
              this.$message.error(response.message)
            }
          })

        } else {
          this.$message.error('请填写表单数据')
          return false;
        }
      });

    }
  }
}
</script>

<template>
  <div id="container">
    <h2>数据可视化后台</h2>
    <el-form :label-position="labelPosition" label-width="80px" :model="form"  :rules="rules" ref="loginForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即登录</el-button>
      </el-form-item>
    </el-form>
    <router-link to="/register">没有账号，立即注册</router-link>
  </div>
</template>

<style scoped>
h2{
  color: #42b983;
  box-sizing: border-box;
}
#container{
  width: 450px;
  height: 350px;
  box-shadow: 0 0 15px #ccc;
  box-sizing: border-box;
  padding: 20px;
  border-radius: 15px;
  margin: 0 auto;
  margin-top: 150px;
  text-align: center;
}
.el-button{
  margin-right: 80px;
}
</style>